package com.llkj.qingnianguoxue.util;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.http.AnsynHttpRequest;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.pingplusplus.android.Pingpp;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 用于处理支付显示弹框，以及支付接口调用
 */

public class PayMethodViewUtil implements DialogUtil.DialogClickListener,AnsynHttpRequest.ObserverCallBack{
    private Context mContext;
    private Activity mActivity;
    private Fragment mFragment;
    private Dialog payMethodDialog;//支付方式弹框
    private String mPayMoney;//支付金额
    private PaySuccessListener mPaySucessListener;
    private int mPayMethod;

    public PayMethodViewUtil(Activity context, PaySuccessListener listener){
        mActivity = context;
        mContext = context;
        payMethodDialog = DialogUtil.showPayMethodDialog(context, this);
        mPaySucessListener = listener;
    }
    public PayMethodViewUtil(Fragment context, PaySuccessListener listener){
        mFragment = context;
        mContext = context.getContext();
        payMethodDialog = DialogUtil.showPayMethodDialog(mFragment.getActivity(), this);
        mPaySucessListener = listener;
    }
    /**
     * 显示支付方式弹框
     */
    public void showPayMethodDialog(String payMoney){
        if(StringUtils.isEmpty(payMoney)){
            ToastUtil.makeLongText(mContext,"对不起,支付金额有误");
            return;
        }
        if(payMethodDialog==null){
            return;
        }
        try {
            mPayMoney = String.format("%.2f", Float.parseFloat(payMoney));
            payMethodDialog.show();
        }catch (Exception e){
            ToastUtil.makeLongText(mContext,"对不起,支付金额有误");
        }
    }

    /**
     * 显示支付方式弹框
     */
    public void showPayMethodDialog(String payMoney, int type){
        if(type==1){
            payMethodDialog.getWindow().findViewById(R.id.tv_balance_pay).setVisibility(View.GONE);
        }

        showPayMethodDialog(payMoney);
    }

    @Override
    public void dialogClick(int type) {
        long money = (long) (Double.valueOf(mPayMoney) * 100);
        String content = null;
        switch (type) {
            case 1://余额
                mPayMethod = 1;
                DialogUtil.showPaySureDialog(mContext, mPayMoney, new DialogUtil.DialogClickListener() {
                    @Override
                    public void dialogClick(int type) {
                        if(type==1){//确认余额支付
                            if (mPaySucessListener!=null) {
                                mPaySucessListener.paySucessResponse(mPayMethod);
                            }
                        }
                    }
                }).show();

                break;
            case 2://微信
                mPayMethod = 3;
                content = "{\"channel\":\"wx\",\"amount\":\"" + money + "\"}";

                AnsynHttpRequest.requestPostString(mContext, HttpMethod.YOUR_URL, content, this, HttpMethod.HTTP_YOUR_URL);
                break;
            case 3://支付宝
                mPayMethod = 2;
                content = "{\"channel\":\"alipay\",\"amount\":\"" + money + "\"}";
                AnsynHttpRequest.requestPostString(mContext, HttpMethod.YOUR_URL, content, this, HttpMethod.HTTP_YOUR_URL);
                break;
            case 4://取消
                break;
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //支付页面返回处理
        if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");
            /* 处理返回值
             * "success" - 支付成功
             * "fail"    - 支付失败
             * "cancel"  - 取消支付
             * "invalid" - 支付插件未安装（一般是微信客户端未安装的情况）
             * "unknown" - app进程异常被杀死(一般是低内存状态下,app进程被杀死)
             */
                String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
                if ("success".equals(result) && mPaySucessListener!=null) {
                    mPaySucessListener.paySucessResponse(mPayMethod);
                }
            }
        }
    }

    @Override
    public void handleResult(String data, int encoding, int method) {
        switch (encoding) {
            case AnsynHttpRequest.SUCCESS_HTTP:
                if (method == HttpMethod.HTTP_YOUR_URL) {
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        if (jsonObject.has("error")) {
                            jsonObject = jsonObject.getJSONObject("error");
                            String message = jsonObject.getString("message");
                            dialogPrompt(message, null, "知道了");
                        } else {
                            if(mActivity!=null){
                                Pingpp.createPayment(mActivity, data);//调起支付控件
                            }else{
                                Pingpp.createPayment(mFragment, data);//调起支付控件
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case AnsynHttpRequest.FAILURE_HTTP:

                break;
            case AnsynHttpRequest.FAILURE_NETWORK:

                break;
        }
    }

    protected Dialog dialogPrompt(String title, String content, String rightBtnName) {
        View dialogView = LayoutInflater.from(mContext).inflate(R.layout.dialog_prompt, null);
        final Dialog dialog = DialogUtil.showDialogCenter(mContext, dialogView, 300);
        TextView tvTitle = (TextView) dialogView.findViewById(R.id.dialog_title);
        TextView tvContent = (TextView) dialogView.findViewById(R.id.dialog_content);
        TextView rigntBtn = (TextView) dialogView.findViewById(R.id.dialog_right_btn);
        if (!StringUtils.isEmpty(title)) {
            tvTitle.setText(title);
        }
        if (!StringUtils.isEmpty(content)) {
            tvContent.setText(content);
            tvContent.setVisibility(View.VISIBLE);
        }
        if (!StringUtils.isEmpty(rightBtnName)) {
            rigntBtn.setText(rightBtnName);
        }
        rigntBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();

            }
        });
        return dialog;
    }

    public interface PaySuccessListener{
        //用于确认余额支付（1，或（0三方支付成功后回调
        void paySucessResponse(int type);
    }
}
